package edu.umn.se.trap.logicChecker;

import java.util.List;
import java.util.Observable;
import java.util.Observer;
import java.util.Vector;

import edu.umn.se.trap.Form;
import edu.umn.se.trap.Grant;
import edu.umn.se.trap.Transportation;
import databases.GrantDB;
import databases.KeyNotFoundException;
import databases.GrantDB.GRANT_FIELDS;
import edu.umn.se.trap.exceptions.TrapException;

public class CheckLogicNIHTransit implements Observer {

    @Override
    /**
     * Update for checking logic of NIH Transit
     */
    public void update(Observable o, Object arg) {
        LogicChecker l1 = (LogicChecker) o;
        Form form = (Form) arg;
        GrantDB grantDB = new GrantDB();
        
        Vector<Grant> grants = form.getGrants();
        int count = 0;
        for (int i = 0; i < grants.size(); i++)
        {
            Grant grant = grants.elementAt(i);
            List<Object> grantInfo;
            
            try {
                grantInfo = grantDB.getGrantInfo(String.valueOf(grant.getAccountNumber()));
                int index = GRANT_FIELDS.FUNDING_ORGANIZATION.ordinal();
                String fundingOrg = (String) grantInfo.get(index);
                if (fundingOrg.equalsIgnoreCase("NIH"))
                {
                    count++;
                }
            } catch (KeyNotFoundException e) {
                l1.setException(new TrapException("Key Invalid - NIH Transit"));
            }
        }
        
        // if all listed grants are from the NIH, then check to for violating transit expenses
        if (count == grants.size())
        {
            Vector<Transportation> transports = form.getTransportation();
            for (int i = 0; i < transports.size(); i++)
            {
                Transportation transport = transports.get(i);
                
                if (!transport.getType().equals("") && !transport.getType().equalsIgnoreCase("air") && !transport.getType().equalsIgnoreCase("public"))
                {
                    l1.setException(new TrapException("NIH will only pay for transit of type 'air' and 'public'"));
                }
            }
        }
    }
}